<?php
chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir(dirname(__FILE__));

include_once $path."/../lib/core.class.php";


class Cart extends IPlugin 
{
    function Cart($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
    }
    
    function getPluginTag() { return "cart"; }
    function getPluginName() { return "Shopping cart plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Cart"; } break;
            case "MenuTitle" : { return "Cart"; } break;
        };
        return $result;
    }
    


    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {

        $result = IPlugin::doAction($params);
        if(NULL != $result || null != $result || FALSE != $result)
        {
            return $result;
        }
        $core = &getCoreInstance();
        $db = $core->getProperty("db");

        $cart = &$_SESSION["cart"];
        if(!is_array($cart))
        {
            $_SESSION["cart"] = array();
            $cart = &$_SESSION["cart"];
        }
        $_SESSION["code_coupon"] = $_POST['code_coupon'];

                                            #################################
                                            ##    ADDING PACKAGE START      #
                                            #################################
                                            
if ('packageadd' == $_POST['event']) {


                unset($_POST['event']);
                ////debug($_POST);
                if($_POST['qty'] > 0){
                        $qty = str2db($_POST['qty']);
                } // end if 
                else{
                        $qty = 1;
                } // end else
                
                if(is_numeric($_POST['warranty_type']) and $_POST['warranty_type'] > 0){
                        $warranty = $_POST['warranty_type'];    
                } // end if
                else{
                        $warranty = 0;
                } // end else
                if(is_numeric($_POST['products_attach_item_parent']) and $_POST['products_attach_item_parent'] > 0){
                        $p_item = str2db($_POST['products_attach_item_parent']);
                }
                else{
                            header("location: ".$core->config['http_root']);
                        exit();
                }
    
                if(is_numeric($_POST['products_attach_item_child']) and $_POST['products_attach_item_child'] > 0){
                        $c_item = str2db($_POST['products_attach_item_child']);
                }
                else{
                            header("location: ".$core->config['http_root']);
                        exit();
                }
                $addingpackage = "true";
} //end if adding package
  



if("true" == $addingpackage and isset($qty,$warranty,$p_item,$c_item)){

    $id = $p_item; 

    if(isset($cart[$id]))
    {
        $cart[$id]["qty"] += $qty;
        $cart[$id]["warranty"] = $warranty;
        $p_stock=$db->getone("select sum(qty) from store_history where catalog_id='$p_item'");
        $c_stock=$db->getone("select sum(qty) from store_history where catalog_id='$c_item'");
        $stock = min($p_stock,$c_stock);    
        if ($cart[$id]["qty"] > $stock) 
        {   // ALARMA !!!
            $cart[$id]["qty"] = $stock;
            
            $GLOBALS[result_recalculate]="<br /><p>Sorry, some requested products are out of stock. </p><br />";
        }
        
        if(0 >= $cart[$id]["qty"])
        {
            unset($cart[$id]);
        }
                        
        }
        else
        {
            $p_data  = $db->getRow("select * from catalog where catalog_id='{$p_item}'");
            $p_price = $p_data['our_price'];
            $c_data  = $db->getRow("select * from catalog where catalog_id='{$c_item}'");
            $c_price = $c_data['list_price'];
            $cart[$id] = array(
            "type" => 'package',
            "package_master" => $p_item,
            "package_slave"  => $c_item,
            "qty" => $qty,
            "price" => $p_price+$c_price,
            "title" => '<b>Package</b><br />'.$p_data['title'].' & '.$c_data['title'],
            "thumbnail" => $p_data["img_small"],
            "pid" => $p_data["parent_id"],
            "warranty" => $warranty);

        } // end else
    
} 
                                            #################################
                                            ##    ADDING PACKAGE ENDS       #
                                            #################################
        
        switch ($_GET["event"]) {
            
            case "add": {
                            $id = $_GET["id"];
                                if($_GET['get'] > 0){
                                                        $qty = $_GET["qty"];
                                }
                                else{
                                        $qty = 1;
                                }
                                        
                $warranty = (isset($_GET['warranty']) && $_GET['warranty'] > 0) ? $_GET['warranty'] : 0;
                if($id>0 && $qty>0)
                {
                    if(isset($cart[$id]))
                    {
                        $cart[$id]["qty"] += $qty;
                        $cart[$id]["warranty"] = $warranty;
                        $stock=$db->getone("select sum(qty) from store_history where catalog_id=$id");
                        if ($cart[$id]["qty"] > $stock) 
                        {   // ALARMA !!!
                            $cart[$id]["qty"] = $stock;
                            $GLOBALS[result_recalculate]="<br>Sorry, some requested products are out of stock.<br>";
                        }
                        if(0 >= $cart[$id]["qty"])
                        {
                            unset($cart[$id]);
                        }

                        
                        
                    }
                    else
                    {
                        $core = &getCoreInstance();
                        $db = $core->getProperty("db");
                        $z = $db->getRow("select parent_id, our_price, title, img_small from catalog where catalog_id={$id}");
                        $cart[$id] = array(
                                    "type" => 'single item',
                                    "qty" => $qty,
                                    "price" => $z["our_price"],
                                    "title" => $z["title"],
                                    "thumbnail" => $z["img_small"],
                                    "pid" => $z["parent_id"],
                                    "warranty" => $warranty,
                                    );
                    }
                }
                        header("location: ".$core->config['http_root'].'index.php?path=cart&id='.$id);
                        exit();

            } break;
            
            case "remove": {
                $id = $_GET["id"];
                $qty = $_GET["qty"];
                if($id>0 && $qty>0)
                {
                    if(isset($cart[$id]))
                    {
                        $cart[$id]["qty"] -= $qty;
                        if(0 >= $cart[$id]["qty"])
                        {
                            unset($cart[$id]);
                        }
                    }
                }
                        header("location: ".$core->config['http_root'].'index.php?path=cart');
                        exit();

            } break;
        
            case "delete": {
                $id = $_GET["id"];
                if($id>0)
                {
                $_SESSION['xcount'] -= 1;                   

                $items-1;                   

                    unset($cart[$id]);
                         unset($_cart[$id]);
                }
                        header("location: ".$core->config['http_root'].'index.php?path=cart');
                        exit();

            } break;
            
            case "recalculate": {
                if (isset($_POST["qty"])){

                        foreach($_POST['qty'] as $k => $v){
                                if($v < 0){
                                        $_POST['qty'][$k] = 1;
                                } 
                        }

                        
                        foreach ($_POST["qty"] as $k => $v)
                        {
                            $stock=$db->getone("select sum(qty) from store_history where catalog_id=$k");
                        if ($v>$stock) 
                        {   // ALARMA !!!
                            $cart[$k]["qty"] = $stock;
                            $GLOBALS[result_recalculate]="<br>Sorry, but some qty out of stock.<br>";
                        }
                        else $cart[$k]["qty"] = $v;
                        }


                }

                        header("location: ".$core->config['http_root'].'index.php?path=cart');
                        exit();
            } break;
        }


        return false;
    }


    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }

        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;
        
        $page = $_GET["page"];
        
        switch ($page)
        {
            default:
                $page = $this->GetCartView($core, $render, $db);
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }
    
    
    
    // ----------------------------------------------------------------------------------
    // --- [ Render cart page ] ---------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function checkImage($file, $folder, &$core, $default="")
    {
        if(file_exists($core->config["file_root"].$folder.$file))
        {
            return $folder.$file;
        }
        return $folder.$default;
    }





    function GetCartView(&$core, &$render, &$db)
    {
        $pid = 0;
        if(isset($_GET["pid"]) && $_GET["pid"]>=0)
        {
            $pid = $_GET["pid"];
        }
        $_cart = $_SESSION["cart"];
                
                
        if(count($_cart)>0)
        {
                        
                        
                        foreach ($_cart as $k => $v)
                        {
                                if (file_exists($core->config["file_root"]."/inventory/".$v[thumbnail]) && is_file($core->config["file_root"]."/inventory/".$v[thumbnail])) {
                                        list($w_size,$h_size)=explode(',',$this->getimgsizes($core->config["file_root"],$v[thumbnail]));
                                        $default_w_size=70;
                                        $default_h_size=77;
                                        $size="";
                                        if ($w_size>$h_size && $w_size>$default_w_size)
                                                $size=" width=\"{$default_w_size}px\" ";
                                        if ($h_size>$w_size && $h_size>$default_h_size)
                                        $size=" height=\"{$default_h_size}px\" ";
                                        
                                        $_cart[$k]['thumbnail'] = "/inventory/".$_cart[$k]['thumbnail'];
                                } else {
                                        $_cart[$k]['thumbnail'] = "/img/no_image.jpg";
                                }
                        }

            $items = 0;
            foreach ($_cart as $k => $v) 
            {
                $items += 1;
                $_SESSION['xcount']= $items;                    
            }
        }
                
            
        
        $xid = $_GET["id"];
        $disc = &$core->getSnippet("discounts");
        $price = 0;
        $code_coupon = (isset($_SESSION["code_coupon"])) ? $_SESSION["code_coupon"] : "";
        $total_discount = 0;


        if(count($_cart)>0)
        {
                $value_warranty = 0;
                    foreach ($_cart as $key => $v)
            {
                $price += $v["qty"] * $v["price"];
                $_cart[$key]["discount"] = $disc->GetValueDiscount($key, $code_coupon, $v["qty"], $v["price"]);
                $_SESSION['xprice'] = $price;
                $_SESSION['cart'][$key]['item_discount'] = (false == $_cart[$key]["discount"]) ? 0 : $_cart[$key]["discount"] / $v["qty"];
                $_cart[$key]["discount"] = $_cart[$key]["discount"];
                $total_discount += $_cart[$key]["discount"];
                                
                $_cart[$key]['cid'] = $db->getone("select parent_id from catalog where catalog_id=$key");
                $_cart[$key]['id'] = $key;
            }

        }
        else
        {
            $_SESSION['xprice'] = 0;
        }
        
        $_SESSION['secure']['total_discount'] = $total_discount;
    
        $render->assign("code_coupon", $code_coupon);

        $itogo = $price - $total_discount;
        if(count($_cart)>0)
        foreach($_cart as $k => $v)
        {
                
                $_cart[$k]['price_nf'] = number_format($_cart[$k]['price'],2,'.',',');
                $_cart[$k]['subtotal'] = ($_cart[$k]['price'] * $_cart[$k]['qty']);
                $_cart[$k]['warranty'] = number_format($value_warranty * $_cart[$k]['qty'],2,'.',',');       
                $_cart[$k]['subtotal'] = number_format($_cart[$k]['subtotal'] - $_cart[$k]['discount'] + $_cart[$k]['warranty'],2,'.',',');             
                $_cart[$k]['discount'] = number_format($_cart[$k]['discount'],2,'.',',');               
                $_cart[$k]['title'] = stripslashes($_cart[$k]['title']);
                $_cart[$k]['qty_on_stock']=$db->getone("select sum(qty) from store_history where catalog_id=$k");
            
            $itogo += $_cart[$k]['warranty'];
        }
                
        $render->assign("cart", $_cart);

        $itogo_nformat = number_format($itogo,2,'.',',');
        $render->assign("price", $itogo_nformat);
        $_SESSION['secure']['price'] = $itogo;
        $_SESSION['xprice'] = $itogo;



        $render->assign("client_id", $this->getSessionCc());

        
        $core = &getCoreInstance();
        $render->assign("host", $core->config['http_root']);
    
        if (isset($_GET["id"]))
        {
            $from_catalog = $db->getone("select parent_id from catalog where catalog_id = $xid");       
            $render->assign("parent_cat", $from_catalog);
        }
                  
        if (isset($GLOBALS['result_recalculate']))
        {
             $render->assign("result_recalculate", $GLOBALS[result_recalculate]);
             unset($GLOBALS['result_recalculate']);
        }                               
        
        return "cart.tpl.php";
    }

        function getSessionCc()                                 {
                $x = $_SESSION['cc']['client_id'];
                return($x);
                        
        }
        
// ----------------------------------------------------------------------------------
// --- [ GET IMAGES SIZE ] ----------------------------------------------------------
// ----------------------------------------------------------------------------------


        function getimgsizes($froot,$img){ 
                if(isne($img) && is_file($froot.'/inventory/'.$img)) {
                        $img = $froot.'/inventory/'.$img;
                        $ar = getimagesize($img);
                        $arrr = $ar[0].','.($ar[1]+50);
                        return $arrr;
                }
                return "";
        } 

        


};


?>